{% extends "base.html" %}
{% block title %}学员档案 - {{ student.real_name }} - 乒乓球培训管理系统{% endblock %}
{% block page_title %}我的档案{% endblock %}

{% block extra_css %}
<style>
.profile-container {
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    border-radius: 20px;
    padding: 0;
    overflow: hidden;
    margin-bottom: 2rem;
    box-shadow: 0 10px 30px rgba(0,0,0,0.2);
}

.profile-header {
    background: rgba(255,255,255,0.1);
    backdrop-filter: blur(10px);
    padding: 2rem;
    color: white;
    position: relative;
}

.profile-header::before {
    content: '';
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background: url('data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1000 1000"><polygon fill="rgba(255,255,255,0.05)" points="0,1000 1000,0 1000,1000"/></svg>');
    pointer-events: none;
}

.profile-content {
    background: white;
    padding: 2rem;
    position: relative;
}

.profile-avatar-large {
    width: 150px;
    height: 150px;
    object-fit: cover;
    border-radius: 50%;
    border: 5px solid rgba(255,255,255,0.3);
    position: relative;
    z-index: 1;
}

.edit-avatar-btn {
    position: absolute;
    bottom: 5px;
    right: 5px;
    width: 40px;
    height: 40px;
    border-radius: 50%;
    background: #007bff;
    border: 3px solid white;
    color: white;
    display: flex;
    align-items: center;
    justify-content: center;
    cursor: pointer;
    transition: all 0.3s ease;
}

.edit-avatar-btn:hover {
    background: #0056b3;
    transform: scale(1.1);
}

.info-section {
    background: white;
    border-radius: 15px;
    box-shadow: 0 5px 15px rgba(0,0,0,0.08);
    padding: 1.5rem;
    margin-bottom: 1.5rem;
    transition: transform 0.2s ease;
}

.info-section:hover {
    transform: translateY(-2px);
}

.section-header {
    display: flex;
    align-items: center;
    justify-content: between;
    margin-bottom: 1.5rem;
    padding-bottom: 0.75rem;
    border-bottom: 2px solid #f8f9fa;
}

.section-title {
    color: #495057;
    font-weight: 600;
    margin: 0;
}

.stat-grid {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
    gap: 1rem;
    margin-bottom: 2rem;
}

.stat-card {
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    color: white;
    padding: 1.5rem;
    border-radius: 12px;
    text-align: center;
    position: relative;
    overflow: hidden;
}

.stat-card::before {
    content: '';
    position: absolute;
    top: -50%;
    right: -50%;
    width: 100%;
    height: 200%;
    background: rgba(255,255,255,0.1);
    transform: rotate(45deg);
}

.stat-value {
    font-size: 2rem;
    font-weight: bold;
    margin-bottom: 0.5rem;
    position: relative;
    z-index: 1;
}

.stat-label {
    font-size: 0.9rem;
    opacity: 0.9;
    position: relative;
    z-index: 1;
}

.coach-item {
    background: #f8f9fa;
    border-radius: 10px;
    padding: 1rem;
    margin-bottom: 1rem;
    border-left: 4px solid #007bff;
    transition: all 0.2s ease;
}

.coach-item:hover {
    background: #e9ecef;
    border-left-color: #0056b3;
}

.coach-avatar {
    width: 60px;
    height: 60px;
    object-fit: cover;
    border-radius: 50%;
}

.reservation-timeline {
    position: relative;
    padding-left: 2rem;
}

.reservation-timeline::before {
    content: '';
    position: absolute;
    left: 0.75rem;
    top: 0;
    bottom: 0;
    width: 2px;
    background: #dee2e6;
}

.timeline-item {
    position: relative;
    margin-bottom: 1.5rem;
    padding: 1rem;
    background: #f8f9fa;
    border-radius: 10px;
    margin-left: 1rem;
}

.timeline-item::before {
    content: '';
    position: absolute;
    left: -1.5rem;
    top: 1.25rem;
    width: 12px;
    height: 12px;
    border-radius: 50%;
    background: #007bff;
    border: 3px solid white;
    box-shadow: 0 0 0 2px #007bff;
}

.edit-form {
    background: #f8f9fa;
    border-radius: 10px;
    padding: 1.5rem;
    margin-top: 1rem;
}

@media (max-width: 768px) {
    .profile-header {
        text-align: center;
        padding: 1.5rem;
    }

    .stat-grid {
        grid-template-columns: repeat(2, 1fr);
        gap: 0.75rem;
    }

    .stat-card {
        padding: 1rem;
    }

    .stat-value {
        font-size: 1.5rem;
    }
}
</style>
{% endblock %}

{% block content %}
<div class="container-fluid">
    <!-- 返回按钮 -->
    {% if can_edit %}
    <div class="mb-3">
        <a href="{{ url_for('dashboard.index') }}" class="btn btn-outline-secondary">
            <i class="bi bi-arrow-left"></i> 返回首页
        </a>
    </div>
    {% else %}
    <div class="mb-3">
        <a href="{{ url_for('students.detail', id=student.id) }}" class="btn btn-outline-secondary">
            <i class="bi bi-arrow-left"></i> 返回学员详情
        </a>
    </div>
    {% endif %}

    <!-- 档案头部 -->
    <div class="profile-container">
        <div class="profile-header">
            <div class="row align-items-center">
                <div class="col-md-3 text-center position-relative">
                    {% if student.photo_url %}
                    <img src="{{ student.photo_url }}" alt="{{ student.real_name }}" class="profile-avatar-large">
                    {% else %}
                    <div class="profile-avatar-large mx-auto bg-white bg-opacity-25 d-flex align-items-center justify-content-center">
                        <i class="bi bi-person-fill" style="font-size: 4rem;"></i>
                    </div>
                    {% endif %}

                    {% if can_edit %}
                    <div class="edit-avatar-btn" onclick="document.getElementById('avatarInput').click()">
                        <i class="bi bi-camera"></i>
                    </div>
                    {% endif %}
                </div>
                <div class="col-md-9">
                    <div class="row">
                        <div class="col-md-8">
                            <h2 class="mb-2">{{ student.real_name }}</h2>
                            <div class="mb-2">
                                <i class="bi bi-telephone me-2"></i>{{ student.phone }}
                            </div>
                            {% if student.email %}
                            <div class="mb-2">
                                <i class="bi bi-envelope me-2"></i>{{ student.email }}
                            </div>
                            {% endif %}
                            <div class="mb-2">
                                <i class="bi bi-building me-2"></i>
                                {{ student.campus.name if student.campus else '未分配校区' }}
                            </div>
                            <div class="mb-0">
                                <i class="bi bi-calendar me-2"></i>
                                注册时间：{{ student.created_at.strftime('%Y年%m月%d日') if student.created_at else '未知' }}
                            </div>
                        </div>
                        <div class="col-md-4 text-end">
                            <div class="mb-2">
                                <span class="badge bg-white text-primary fs-6 px-3 py-2">
                                    {% if student.gender == 'male' %}
                                        <i class="bi bi-gender-male me-1"></i>男性
                                    {% elif student.gender == 'female' %}
                                        <i class="bi bi-gender-female me-1"></i>女性
                                    {% else %}
                                        <i class="bi bi-question-circle me-1"></i>未设置
                                    {% endif %}
                                </span>
                            </div>
                            {% if student.age %}
                            <div class="mb-2">
                                <span class="badge bg-white text-info fs-6 px-3 py-2">
                                    <i class="bi bi-cake me-1"></i>{{ student.age }}岁
                                </span>
                            </div>
                            {% endif %}
                            <div>
                                <span class="badge {% if student.status == 'active' %}bg-success{% else %}bg-secondary{% endif %} fs-6 px-3 py-2">
                                    <i class="bi bi-circle-fill me-1" style="font-size: 0.5rem;"></i>
                                    {% if student.status == 'active' %}活跃学员{% else %}不活跃{% endif %}
                                </span>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <div class="profile-content">
            <!-- 统计概览 -->
            <div class="stat-grid">
                <div class="stat-card" style="background: linear-gradient(135deg, #11998e 0%, #38ef7d 100%);">
                    <div class="stat-value">{{ statistics.total_coaches }}</div>
                    <div class="stat-label">我的教练</div>
                </div>
                <div class="stat-card" style="background: linear-gradient(135deg, #fc4a1a 0%, #f7b733 100%);">
                    <div class="stat-value">{{ statistics.total_reservations }}</div>
                    <div class="stat-label">预约次数</div>
                </div>
                <div class="stat-card" style="background: linear-gradient(135deg, #4776e6 0%, #8e54e9 100%);">
                    <div class="stat-value">{{ statistics.total_hours }}</div>
                    <div class="stat-label">学习时长(小时)</div>
                </div>
                <div class="stat-card" style="background: linear-gradient(135deg, #ff6b6b 0%, #feca57 100%);">
                    <div class="stat-value">¥{{ statistics.total_spending }}</div>
                    <div class="stat-label">总消费</div>
                </div>
            </div>
        </div>
    </div>

    <div class="row">
        <!-- 左侧：基本信息和编辑 -->
        <div class="col-md-6">
            <!-- 基本信息编辑 -->
            {% if can_edit %}
            <div class="info-section">
                <div class="section-header">
                    <h5 class="section-title">
                        <i class="bi bi-pencil-square me-2"></i>编辑基本信息
                    </h5>
                </div>

                <form method="POST" enctype="multipart/form-data" id="profileForm">
                    {{ form.hidden_tag() if form }}
                    <input type="file" id="avatarInput" style="display: none;" accept="image/*">

                    <div class="edit-form">
                        <div class="row">
                            {% if form %}
                            <div class="col-md-6">
                                <div class="form-floating mb-3">
                                    {{ form.real_name(class="form-control") }}
                                    {{ form.real_name.label(class="form-label") }}
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="form-floating mb-3">
                                    {{ form.email(class="form-control") }}
                                    {{ form.email.label(class="form-label") }}
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="form-floating mb-3">
                                    {{ form.gender(class="form-select") }}
                                    {{ form.gender.label(class="form-label") }}
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="form-floating mb-3">
                                    {{ form.age(class="form-control") }}
                                    {{ form.age.label(class="form-label") }}
                                </div>
                            </div>
                            {% endif %}
                        </div>

                        {% if form %}
                        <div class="text-center">
                            <button type="submit" class="btn btn-primary me-2">
                                <i class="bi bi-check-lg me-2"></i>保存修改
                            </button>
                            <button type="button" class="btn btn-outline-secondary" onclick="resetForm()">
                                <i class="bi bi-arrow-clockwise me-2"></i>重置
                            </button>
                        </div>
                        {% endif %}
                    </div>
                </form>
            </div>
            {% else %}
            <!-- 只读信息展示 -->
            <div class="info-section">
                <div class="section-header">
                    <h5 class="section-title">
                        <i class="bi bi-person-lines-fill me-2"></i>基本信息
                    </h5>
                </div>

                <div class="row">
                    <div class="col-6">
                        <div class="mb-3">
                            <label class="form-label text-muted">真实姓名</label>
                            <div class="fw-bold">{{ student.real_name }}</div>
                        </div>
                    </div>
                    <div class="col-6">
                        <div class="mb-3">
                            <label class="form-label text-muted">手机号</label>
                            <div class="fw-bold">{{ student.phone }}</div>
                        </div>
                    </div>
                    <div class="col-6">
                        <div class="mb-3">
                            <label class="form-label text-muted">邮箱</label>
                            <div class="fw-bold">{{ student.email or '未设置' }}</div>
                        </div>
                    </div>
                    <div class="col-6">
                        <div class="mb-3">
                            <label class="form-label text-muted">年龄</label>
                            <div class="fw-bold">{{ student.age or '未设置' }}</div>
                        </div>
                    </div>
                </div>
            </div>
            {% endif %}

            <!-- 账户信息 -->
            <div class="info-section">
                <div class="section-header">
                    <h5 class="section-title">
                        <i class="bi bi-wallet2 me-2"></i>账户信息
                    </h5>
                    {% if can_edit %}
                    <a href="{{ url_for('accounts.balance') }}" class="btn btn-sm btn-outline-primary">
                        <i class="bi bi-eye"></i> 查看详情
                    </a>
                    {% endif %}
                </div>

                <div class="row">
                    <div class="col-4">
                        <div class="text-center p-3 bg-light rounded">
                            <div class="h4 text-success mb-1">¥{{ statistics.account_balance or '0.00' }}</div>
                            <small class="text-muted">账户余额</small>
                        </div>
                    </div>
                    <div class="col-4">
                        <div class="text-center p-3 bg-light rounded">
                            <div class="h4 text-primary mb-1">{{ statistics.completed_reservations }}</div>
                            <small class="text-muted">已完成课程</small>
                        </div>
                    </div>
                    <div class="col-4">
                        <div class="text-center p-3 bg-light rounded">
                            <div class="h4 text-warning mb-1">{{ statistics.pending_reservations }}</div>
                            <small class="text-muted">待上课程</small>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- 右侧：教练和预约信息 -->
        <div class="col-md-6">
            <!-- 我的教练 -->
            <div class="info-section">
                <div class="section-header">
                    <h5 class="section-title">
                        <i class="bi bi-people me-2"></i>我的教练 ({{ coaches|length }})
                    </h5>
                    {% if can_edit %}
                    <a href="{{ url_for('students.apply_coach', id=student.id) }}" class="btn btn-sm btn-outline-primary">
                        <i class="bi bi-plus"></i> 申请教练
                    </a>
                    {% endif %}
                </div>

                {% if coaches %}
                {% for coach in coaches %}
                <div class="coach-item">
                    <div class="d-flex align-items-center">
                        {% if coach.photo_url %}
                        <img src="{{ coach.photo_url }}" alt="{{ coach.real_name }}" class="coach-avatar me-3">
                        {% else %}
                        <div class="coach-avatar me-3 bg-light d-flex align-items-center justify-content-center">
                            <i class="bi bi-person-fill text-muted"></i>
                        </div>
                        {% endif %}
                        <div class="flex-grow-1">
                            <h6 class="mb-1">{{ coach.real_name }}</h6>
                            <div class="text-muted">
                                <small>{{ coach.coach_level }}级教练 • ¥{{ coach.hourly_rate }}/小时</small>
                            </div>
                            <div class="mt-1">
                                <span class="badge bg-success">合作中</span>
                            </div>
                        </div>
                        {% if can_edit %}
                        <div>
                            <a href="#" class="btn btn-sm btn-outline-info">
                                <i class="bi bi-chat"></i> 联系
                            </a>
                        </div>
                        {% endif %}
                    </div>
                </div>
                {% endfor %}
                {% else %}
                <div class="text-center py-4 text-muted">
                    <i class="bi bi-person-x display-6"></i>
                    <p class="mt-2">暂无关联教练</p>
                    {% if can_edit %}
                    <a href="{{ url_for('students.apply_coach', id=student.id) }}" class="btn btn-primary">
                        <i class="bi bi-plus"></i> 申请教练
                    </a>
                    {% endif %}
                </div>
                {% endif %}
            </div>

            <!-- 最近预约 -->
            <div class="info-section">
                <div class="section-header">
                    <h5 class="section-title">
                        <i class="bi bi-calendar-event me-2"></i>最近预约
                    </h5>
                    {% if can_edit %}
                    <a href="{{ url_for('student_reservations.index') }}" class="btn btn-sm btn-outline-info">
                        <i class="bi bi-eye"></i> 查看全部
                    </a>
                    {% endif %}
                </div>

                {% if recent_reservations %}
                <div class="reservation-timeline">
                    {% for reservation in recent_reservations %}
                    <div class="timeline-item">
                        <div class="d-flex justify-content-between align-items-start">
                            <div class="flex-grow-1">
                                <h6 class="mb-1">
                                    球台 {{ reservation.table.name if reservation.table else '未知' }}
                                    {% if reservation.coach %}
                                    • {{ reservation.coach.real_name }}
                                    {% endif %}
                                </h6>
                                <div class="text-muted mb-1">
                                    <i class="bi bi-clock me-1"></i>
                                    {{ reservation.start_time.strftime('%m-%d %H:%M') }} -
                                    {{ reservation.end_time.strftime('%H:%M') }}
                                </div>
                                <div class="text-muted">
                                    <i class="bi bi-cash me-1"></i>¥{{ reservation.price }}
                                </div>
                            </div>
                            <div>
                                <span class="badge
                                      {% if reservation.status == 'completed' %}bg-success
                                      {% elif reservation.status == 'pending' %}bg-warning
                                      {% elif reservation.status == 'cancelled' %}bg-danger
                                      {% else %}bg-info{% endif %}">
                                    {% if reservation.status == 'completed' %}已完成
                                    {% elif reservation.status == 'pending' %}待确认
                                    {% elif reservation.status == 'cancelled' %}已取消
                                    {% else %}{{ reservation.status }}{% endif %}
                                </span>
                            </div>
                        </div>
                    </div>
                    {% endfor %}
                </div>
                {% else %}
                <div class="text-center py-4 text-muted">
                    <i class="bi bi-calendar-x display-6"></i>
                    <p class="mt-2">暂无预约记录</p>
                    {% if can_edit %}
                    <a href="{{ url_for('student_reservations.create') }}" class="btn btn-primary">
                        <i class="bi bi-plus"></i> 立即预约
                    </a>
                    {% endif %}
                </div>
                {% endif %}
            </div>
        </div>
    </div>
</div>
{% endblock %}

{% block extra_js %}
<script>
// 头像上传处理
document.getElementById('avatarInput').addEventListener('change', function(e) {
    const file = e.target.files[0];
    if (file) {
        // 验证文件类型
        const allowedTypes = ['image/jpeg', 'image/png', 'image/gif'];
        if (!allowedTypes.includes(file.type)) {
            alert('请选择 JPG、PNG 或 GIF 格式的图片');
            this.value = '';
            return;
        }

        // 验证文件大小 (5MB)
        if (file.size > 5 * 1024 * 1024) {
            alert('图片大小不能超过 5MB');
            this.value = '';
            return;
        }

        // 自动提交头像更新
        const formData = new FormData();
        formData.append('photo', file);
        formData.append('csrf_token', document.querySelector('input[name="csrf_token"]').value);

        // 显示上传状态
        const avatar = document.querySelector('.profile-avatar-large');
        const originalSrc = avatar.src;

        fetch('{{ url_for("students.profile", id=student.id) }}', {
            method: 'POST',
            body: formData
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                // 更新头像显示
                const reader = new FileReader();
                reader.onload = function(e) {
                    avatar.src = e.target.result;
                };
                reader.readAsDataURL(file);

                alert('头像更新成功！');
            } else {
                alert('头像更新失败：' + (data.error || '未知错误'));
                avatar.src = originalSrc;
            }
        })
        .catch(error => {
            console.error('头像上传失败:', error);
            alert('头像上传失败，请重试');
            avatar.src = originalSrc;
        });
    }
});

// 重置表单
function resetForm() {
    document.getElementById('profileForm').reset();
}

// 表单提交处理
{% if can_edit and form %}
document.getElementById('profileForm').addEventListener('submit', function(e) {
    e.preventDefault();

    const formData = new FormData(this);
    const submitBtn = this.querySelector('button[type="submit"]');
    const originalText = submitBtn.innerHTML;

    // 显示提交状态
    submitBtn.innerHTML = '<i class="bi bi-hourglass-split me-2"></i>保存中...';
    submitBtn.disabled = true;

    fetch('{{ url_for("students.profile", id=student.id) }}', {
        method: 'POST',
        body: formData
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            alert('档案更新成功！');
            location.reload(); // 刷新页面显示最新数据
        } else {
            alert('更新失败：' + (data.error || '未知错误'));
        }
    })
    .catch(error => {
        console.error('提交失败:', error);
        alert('提交失败，请重试');
    })
    .finally(() => {
        submitBtn.innerHTML = originalText;
        submitBtn.disabled = false;
    });
});
{% endif %}

// 定时刷新统计数据
function refreshStatistics() {
    fetch('{{ url_for("students.api_statistics", id=student.id) }}')
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                // 更新统计卡片
                const stats = data.data;
                updateStatCard(0, stats.total_coaches);
                updateStatCard(1, stats.total_reservations);
                updateStatCard(2, stats.total_hours);
                updateStatCard(3, '¥' + stats.total_spending);

                // 更新账户信息
                updateAccountInfo(stats);
            }
        })
        .catch(error => console.error('获取统计数据失败:', error));
}

// 更新统计卡片
function updateStatCard(index, value) {
    const cards = document.querySelectorAll('.stat-card .stat-value');
    if (cards[index]) {
        cards[index].textContent = value;
    }
}

// 更新账户信息
function updateAccountInfo(stats) {
    const balanceEl = document.querySelector('.text-success.h4');
    const completedEl = document.querySelector('.text-primary.h4');
    const pendingEl = document.querySelector('.text-warning.h4');

    if (balanceEl) balanceEl.textContent = '¥' + (stats.account_balance || '0.00');
    if (completedEl) completedEl.textContent = stats.completed_reservations;
    if (pendingEl) pendingEl.textContent = stats.pending_reservations;
}

// 页面加载完成后刷新数据
document.addEventListener('DOMContentLoaded', function() {
    refreshStatistics();
});

// 定时刷新数据
setInterval(refreshStatistics, 120000); // 每2分钟刷新一次
</script>
{% endblock %}